/**
 * 初始化项目
 * 2016.9.6
 */
const child_process = require('child_process');
var colors;

check('cnpm', () => checkPkg('colors', installPkg));
function installPkg() {
	try{
		colors = require('colors');
	}catch(e){
		setTimeout(installPkg, 300);
		return;
	}

	install('fis3-hook-relative'); //https://github.com/fex-team/fis3-hook-relative
	install('fis3-parser-html-uri'); //https://github.com/fancyboynet/fis3-parser-html-uri
	install('fis3-parser-typescript'); //https://github.com/fex-team/fis3-parser-typescript
	install('node-sass');//https://github.com/sass/node-sass
	install('fis3-parser-node-sass'); //https://github.com/fex-team/fis-parser-node-sass
	install('fis3-postprocessor-autoprefixer'); //https://github.com/huixisheng/fis3-postprocessor-autoprefixer
	install('fis-parser-swig');//https://github.com/scott-wong/fis-parser-swig
	install('fis3-hook-node_modules'); //https://github.com/fex-team/fis3-hook-node_modules
	install('fis3-hook-amd'); //https://github.com/fex-team/fis3-hook-amd
	install('fis3-parser-vue-component'); //https://github.com/ccqgithub/fis3-parser-vue-component
	install('fis3-preprocessor-js-require-css'); //https://github.com/fex-team/fis3-preprocessor-js-require-css
	install('fis3-preprocessor-js-require-file'); //https://github.com/fex-team/fis3-preprocessor-js-require-file
	install('fis3-postpackager-loader'); //https://github.com/fex-team/fis3-postpackager-loader
	install('fis3-packager-deps-pack'); //https://github.com/fex-team/fis3-packager-deps-pack
	install('fis-optimizer-tinify'); //https://github.com/zswang/fis-optimizer-tinify
	install('fis3-deploy-skip-packed'); //https://github.com/fex-team/fis3-deploy-skip-packed
	//install(''); //
}



function check(name, resolve) {
    console.log('----------check:' + name);
    child_process.exec(name + ' -v', function(err, data) {
        if (err) {
            install(name, resolve);
            return;
        }
        resolve();
    });
}

function checkPkg(name, resolve) {
    console.log('----------checkPkg:' + name);
    var mod;
    try {
        mod = require(name);
    } catch (e) {
        //throw e;
    } finally {
        if (undefined === mod) {
            install(name, resolve);
        }else{
        	resolve();
        }
    }
}




function install(name, resolve) {
    console.log('----------install:' + name);
    var url = '';
    if (name === 'cnpm') {
        url = 'npm install -g cnpm --registry=https://registry.npm.taobao.org';
    } else {
        url = 'cnpm install -g ' + name;
    }
    child_process.exec(url, function(err, data) {
        if (err) {
            console.log('[error]' + name + '安装失败！');
            console.log(err);
            return;
        }
    	colors&&console.log('----------install:'.green + name.bgGreen);
        resolve&&resolve();
    });
}
